package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignSerivce;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {


    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    WareFeignSerivce wareFeignSerivce;
    @Autowired
    SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * TODO 高级部分再来完善代码
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        // 1、保存spu基本信息（pms_spu_info）
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        Long spuInfoEntityId = spuInfoEntity.getId();

        // 2、保存spu的描述图片（pms_spu_info_desc）
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntityId);
        if (!CollectionUtils.isEmpty(decript)) {
            descEntity.setDecript(String.join(",", decript));
        }
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        // 3、保存spu的图片集（pms_spu_images）
        List<String> imageList = vo.getImages();
        spuImagesService.saveImageList(spuInfoEntityId, imageList);

        // 4、保存spu的规格参数（pms_product_attr_value）
        List<BaseAttrs> baseAttrsList = vo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValueEntityList = baseAttrsList.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity == null ? "" : attrEntity.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfoEntityId);
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(attrValueEntityList);

        // 5、保存spu的积分信息（[gulimall_sms]-sms_spu_bounds）
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntityId);
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        // 6、保存当前spu对应的所有 sku信息
        List<Skus> skuList = vo.getSkus();
        if (!CollectionUtils.isEmpty(skuList)) {
            skuList.forEach(sku -> {
                // 6.1)、sku的基本信息（pms_sku_info）
                String defaultImage = "";
                List<Images> images = sku.getImages();
                if (!CollectionUtils.isEmpty(images)) {
                    for (Images image : images) {
                        if (image.getDefaultImg() == 1) {
                            defaultImage = image.getImgUrl();
                        }
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                // 自增主键
                Long skuId = skuInfoEntity.getSkuId();

                // 6.2)、sku的图片信息（pms_sku_images）
                if (!CollectionUtils.isEmpty(images)) {
                    List<SkuImagesEntity> skuImagesEntityList = images.stream()
                            .map(img -> {
                                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                                skuImagesEntity.setSkuId(skuId);
                                skuImagesEntity.setImgUrl(img.getImgUrl());
                                skuImagesEntity.setDefaultImg(img.getDefaultImg());
                                return skuImagesEntity;
                            }).filter(o -> StringUtil.isNotEmpty(o.getImgUrl()))
                            .collect(Collectors.toList());
                    skuImagesService.saveBatch(skuImagesEntityList);
                }

                // 6.3)、sku的销售属性信息（pms_sku_sale_attr_value）
                List<Attr> attrList = sku.getAttr();
                if (!CollectionUtils.isEmpty(attrList)) {
                    List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attrList.stream().map(attr -> {
                        SkuSaleAttrValueEntity valueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr, valueEntity);
                        valueEntity.setSkuId(skuId);
                        return valueEntity;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);

                }

                // 6.4)、sku的优惠、满减等信息（[gulimall_sms]-sms_sku_ladder + sms_sku_full_reduction + sms_member_price）
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0) {
                    R savedSkuReductionResult = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (savedSkuReductionResult.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }

            });


        }








    }


    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        if (CollectionUtils.isEmpty(params)) {
            return null;
        }

        // 准备查询条件
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        String status = (String) params.get("status");
        String brandId = (String) params.get("brandId");
        String catelogId = (String) params.get("catelogId");
        if (StringUtil.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        if (StringUtil.isNotEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        if (StringUtil.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        if (StringUtil.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }



    @Override
    public void up(Long spuId) {
        if (spuId == null) {
            log.error("[SpuInfoServiceImpl-up] 入参中的 spuId 为空，无法上架");
            return;
        }

        // 1、查出当前 spuId 对应的所有 sku信息
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.getSkuListBySpuId(spuId);
        if (CollectionUtils.isEmpty(skuInfoEntityList)) {
            return;
        }

        // 查询sku的所有支持检索的规格属性（规格属性是跟着SPU走的）
        List<SkuEsModel.Attrs> attrsList = new ArrayList<>();
        List<ProductAttrValueEntity> productAttrList = productAttrValueService.baseAttrListForSpu(spuId);
        if (!CollectionUtils.isEmpty(productAttrList)) {
            List<Long> productAttrIdList = productAttrList.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(productAttrIdList)) {
                // 查询到支持检索的属性id
                List<Long> searchAttrIdList = attrService.selectSearchAttrIdList(productAttrIdList);
                // 过滤出支持检索的属性
                attrsList = productAttrList.stream()
                        .filter(attr -> searchAttrIdList.contains(attr.getAttrId()))
                        .map(item -> {
                            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                            BeanUtils.copyProperties(item, attrs);
                            return attrs;
                        })
                        .collect(Collectors.toList());
            }
        }

        // 查询sku是否有库存
        List<SkuHasStockVo> stockVoList = new ArrayList<>();
        List<Long> skuIdList = skuInfoEntityList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(skuIdList)) {
            try {
                R skuHasStockR = wareFeignSerivce.getSkuHasStock(skuIdList);
                TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
                };
                if (skuHasStockR.getCode() != 0) {
                    log.error("[SpuInfoServiceImpl-up] 通过feign调用ware服务，根据skuIdList查询是否有库存。调用失败，返回错误码为：{}", skuHasStockR.getCode());
                } else {
                    // TODO 老师把 R 中加了泛型，然后改了代码。我这边暂时没改
                    stockVoList = skuHasStockR.getData(typeReference);
                }
            } catch (Exception e) {
                log.error("[SpuInfoServiceImpl-up] 通过feign调用ware服务，根据skuIdList查询是否有库存。出现异常，异常信息为：", e);
            }
        }
        Map<Long, Boolean> skuHasStockMap;
        if (!CollectionUtils.isEmpty(stockVoList)) {
            skuHasStockMap = stockVoList.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } else {
            skuHasStockMap = null;
        }


        // 2、封装每个sku的信息
        List<SkuEsModel.Attrs> finalAttrsList = attrsList;
        List<SkuEsModel> upList = skuInfoEntityList.stream().map(sku -> {
            // 组装数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            // 1、调用库存服务，查询是否有库存
            if (skuHasStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(skuHasStockMap.get(sku.getSkuId()));
            }

            // 2、热度评分：默认给个0
            esModel.setHotScore(0L);

            // 3、查询品牌和分类信息 并组装
            BrandEntity brandEntity = brandService.getById(esModel.getBrandId());
            if (brandEntity != null) {
                esModel.setBrandName(brandEntity.getName());
                esModel.setBrandImg(brandEntity.getLogo());
            }
            CategoryEntity categoryEntity = categoryService.getById(esModel.getCatalogId());
            if (categoryEntity != null) {
                esModel.setCatalogName(categoryEntity.getName());
            }

            // 4、组装当前sku的所有支持检索的规格属性
            esModel.setAttrs(finalAttrsList);

            return esModel;
        }).collect(Collectors.toList());


        // 5 将数据发送给 ES 进行保存
        R r = searchFeignService.productStatusUp(upList);
        if (r.getCode() == 0) {
            // 远程调用成功
            // 6、修改当前 spu 为上架状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());

        } else {
            // 远程调用失败
            // TODO 7、重复调用？ 接口幂等性？ 重试机制？
        }

    }

}
















































